﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using GU.WebERP.Model;
using YGOP.ESB.Log.Model;
using YGOP.ESB.Log;

namespace GU.WebERPApp.App_Code
{
    public class BasePage : System.Web.UI.Page
    {
        private Model_Fct_User _CurrentUser = null;
        public Model_Fct_User CurrentUser
        {
            get
            {
                if (_CurrentUser == null)
                {
                    _CurrentUser = Session["User"] as Model_Fct_User;
                }
                return _CurrentUser;
            }
        }

        protected override void OnLoad(EventArgs e)
        {
            if (Request.UserHostAddress.Contains("127.") || Request.UserHostAddress.Contains("172.") ||
                Request.UserHostAddress.Contains("::1") || Request.UserHostAddress.Contains("192.168.") ||
                Request.UserHostAddress.Contains("182."))
            {
                if (CurrentUser == null)
                {
                    Response.Redirect("/Login.aspx", true);
                }

                if (CurrentUser.IsAdmin == 0)
                {
                    string path = Request.Path.ToLower();
                    if (!ValidationMenuRights(CurrentUser.UserMenu, path))
                    {
                        Response.Write("对不起，你没有该页面的访问权限！");
                        Response.End();
                    }
                }

                EsbUserLog log = new EsbUserLog();
                log.Behavior = "ViewPage";
                log.UserName = "";
                log.UserIP = this.Request.UserHostAddress;
                log.PageUrl = this.Request.Url.AbsoluteUri;
                log.UrlReferrer = this.Request.UrlReferrer == null ? null : this.Request.UrlReferrer.ToString();
                LogManager.WriteEsbUserLog(log);
            }
            else
            {
                Response.StatusCode = 404;
                Response.End();
                return;
            }
            base.OnLoad(e);
        }

        private bool ValidationMenuRights(List<MiniUi_Menu> menus, string path)
        {
            if (path.Contains("index.aspx")) return true;

            foreach (MiniUi_Menu item in menus)
            {
                if (string.IsNullOrWhiteSpace(item.url)) continue;
                if (path.Contains(item.url.ToLower()))
                {
                    return true;
                }
            }
            return false;
        }
    }
}